#include "ChatCinema.hpp"

ChatCinema::ChatCinema(const std::string& roomName, const std::string& hostname, ConnectionPtr hostConnection) {
    roomName_ = roomName;
    roomHost_ = hostname;
    users_.insert(hostname);
    if (hostConnection) userConnections_[hostname] = std::weak_ptr<TcpConnection>(hostConnection);
}


ChatCinema::~ChatCinema(){

}

bool ChatCinema::addUser(const std::string& username, ConnectionPtr userconnection) {
    // 没有用户时，加入用户；有用户时，若connection存在且在线，则不加入，若connection不存在或掉线，加入新connection；
    if (users_.find(username) == users_.end()) {
        users_.insert(username);
        if (userconnection) userConnections_[username] = std::weak_ptr<TcpConnection> (userconnection);
    }
    else if (userConnections_.find(username) == userConnections_.end() || userConnections_[username].expired()) {
        if (userconnection) userConnections_[username] = std::weak_ptr<TcpConnection> (userconnection);
    }
    else {
        return false; // 该用户存在，且在线
    }
    return true;
}



void ChatCinema::removeUser(const std::string& username) {
    if (users_.find(username) != users_.end()) {
        users_.erase(username);
    }
    
    if (userConnections_.find(username) == userConnections_.end()) {
        userConnections_.erase(username);
    }
}

bool ChatCinema::haveUser(const std::string& username) {
    if (users_.find(username) == users_.end()) {
        return false;
    }
    return true;
}